import React, { Component } from 'react';
import { ShopState, ShopItem } from './interface/index.d';
import { store } from './store/index';
import CartList from './CartList.component';

export default class Shop extends Component<{}, ShopState> {
  selectedShopItem: any;
  constructor(props: {}) {
    super(props);

    this.updateState = this.updateState.bind(this);
    this.handleAddCart = this.handleAddCart.bind(this);
    store.subscribe(this.updateState);
  }
  readonly state = store.getState().shopReducer;

  render() {
    return (
      <div>
        {
          this.state.list.map((item, index) => {
            return (
              <p key={item.id}>
                <input type="checkbox" checked={item.checked} onChange={this.handleCheck.bind(this, item)} />
                <span>{item.name}</span>
                <span> {item.unit_price}元</span>
                <button onClick={this.handleSubtract.bind(this, item.id)}>-</button>{item.quantity}<button onClick={this.handleAdd.bind(this, item.id)}>+</button>
              </p>
            )
          })
        }
        <div><button onClick={this.handleAddCart}>加入购物车</button></div>
        <CartList />
      </div>
    )
  }

  handleAddCart() {
    const action = {
      type: 'ADD_TO_CART',
      item: this.state.list[0]
    };

    store.dispatch(action);
  }

  handleCheck(item: ShopItem) {
    const action = {
      type: 'CHECK_GOOD_ITEM',
      item
    };
    store.dispatch(action);
  }

  handleSubtract(id: number) {
    const action = {
      type: 'SUB_GOOD_ITEM',
      id
    };
    store.dispatch(action);
  }

  handleAdd(id: number) {
    const action = {
      type: 'ADD_GOOD_ITEM',
      id
    };
    store.dispatch(action);
  }

  private updateState() {
    this.setState(store.getState().shopReducer);
  }
}
